<?php
namespace app\lib\exception;

use Exception;
use think\exception\Handle;
use think\Request;
use think\Log;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $error_code;
    public function render(\Exception $e)
    {
        if($e instanceof CommonException){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->error_code = $e->error_code;
        }else{
            if(config('app_debug')){
                return parent::render($e);
            }else{
                $this->code = 500;
                $this->msg = '系统错误，请重试';
                $this->error_code = 999;
                $errorMsg = $e->getMessage().' 在 '.$e->getFile().' '.$e->getLine().' 行'.$e->getTraceAsString();
                Log::record($errorMsg,'error');
                //$this->recordErrorLog($e);
            }
        }
        $request = Request::instance();
        
        $result = [
            'msg' => $this->msg,
            'error_code' => $this->error_code,
            'request_url' => $request->url()
        ];
        return json($result,$this->code);
    }
    
    private function recordErrorLog(Exception $e)
    {
        Log::init([
            // 日志记录方式，内置 file socket 支持扩展
            'type'  => 'File',
            'path'  => LOG_PATHS,
            'level' => ['error']
        ]);
        Log::record($e->getMessage(),'error');
    }
}
